﻿Imports System.ComponentModel.Composition
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Windows.Input
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor

Namespace Microsoft.VisualStudio.RegularExpression.LaunchingPoints
	''' <summary>
	''' Handles the key pressed event to launch the regex editor.
	''' </summary>
	Friend Class LaunchEditorKeyProcessor
		Inherits KeyProcessor
		Private ReadOnly Shared NewRegexStatementForCSharpOrVisualBasic As New Regex("[nN]ew\s+(Regex|System\.Text\.RegularExpressions\.Regex)$", RegexOptions.Singleline Or RegexOptions.Compiled)

		Private view As IWpfTextView
		Private regexEditorService As RegexEditorService
		Private keyTypeConverter As KeyTypeConverter

		Friend Sub New(ByVal view As IWpfTextView, ByVal regexEditorService As RegexEditorService)
			Me.view = view
			Me.regexEditorService = regexEditorService

            Me.keyTypeConverter = New KeyTypeConverter
		End Sub

		Public Overrides Sub KeyDown(ByVal args As KeyEventArgs)
            Dim key? = Me.keyTypeConverter.ConvertToChar(args.Key)
			' Check if the parethesis key was pressed
			If key.HasValue AndAlso key.Value = "("c Then
				' Create a regex line data
                Dim lineData = RegexLineData.CreateFromCaretPosition(Me.view)

                ' Check if the line contains a new Regex statement
                If IsValid(lineData) Then
                    Me.view.TextBuffer.Insert(lineData.CaretPosition, key.ToString())
                    ' Show the regex editor
                    Dim editorResult = Me.regexEditorService.ShowEditor()
                    ' Insert the edited pattern in the line
                    If editorResult.Result.HasValue AndAlso editorResult.Result.Value Then
                        Me.view.TextBuffer.Insert(lineData.CaretPosition + 1, String.Format("@""{0}""", editorResult.Pattern))
                    End If

                    args.Handled = True
                End If
			End If
		End Sub

		''' <summary>
		''' Returns true if the regex line ends with a "new Regex" statement (for C# or VB)
		''' </summary>
		''' <param name="regexLineData"></param>
		''' <returns></returns>
		Private Function IsValid(ByVal regexLineData As RegexLineData) As Boolean
			Return NewRegexStatementForCSharpOrVisualBasic.IsMatch(regexLineData.Text.TrimEnd())
		End Function
	End Class
End Namespace